package com.hyg.lib_music.ui.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.request.RequestOptions;
import com.hyg.lib_common.Base.BaseActivity;
import com.hyg.lib_common.DataModel.EventBusMessage;
import com.hyg.lib_common.DataModel.Music.Music;
import com.hyg.lib_common.Net.CommonHttpUtil;
import com.hyg.lib_common.constant.Constants;
import com.hyg.lib_music.R;
import com.hyg.lib_music.adapter.MusicCategorySecondAdapter;
import com.hyg.lib_music.adapter.MusicPlayListAdapter;
import com.hyg.lib_music.databinding.ActivityCategoryMusicListBinding;
import com.hyg.lib_music.modle.CategoryMusicListData;
import com.hyg.lib_music.modle.CategoryMusicThreeData;
import com.hyg.lib_music.modle.NewMusicCategoryData;
import com.hyg.lib_music.modle.RecommedMusicData;
import com.hyg.lib_music.service.MusicService;
import com.jaeger.library.StatusBarUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class CategoryMusicListActivity extends BaseActivity {
    ActivityCategoryMusicListBinding binding;
    String imageUrl;
    int id;
    CategoryMusicThreeData.DataDTO dataDTO;
    List<CategoryMusicThreeData.DataDTO> list = new ArrayList<>();
    ArrayList<Music> music_list = new ArrayList<>();
    MusicPlayListAdapter mAdapter;
    boolean needRefresh = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityCategoryMusicListBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        init();
    }

    public void init() {
        StatusBarUtil.setTransparentForImageViewInFragment(CategoryMusicListActivity.this, null);
        imageUrl = getIntent().getStringExtra("imageUrl");
        dataDTO = getIntent().getParcelableExtra("data");
        if (!TextUtils.isEmpty(imageUrl)) {
            Glide.with(this).load(imageUrl).into(binding.ivTopImage);
        }
        if (dataDTO != null) {
            RoundedCorners roundedCorners = new RoundedCorners(30);//数字为圆角度数
            RequestOptions coverRequestOptions = new RequestOptions()
                    .transforms(new CenterCrop(), roundedCorners)
                    .diskCacheStrategy(DiskCacheStrategy.NONE)//不做磁盘缓存
                    .skipMemoryCache(true);//不做内存缓存
            Glide.with(this).load(dataDTO.logoUrl)
                    .apply(coverRequestOptions).into(binding.ivSortsImage);
            binding.tvTitle.setText(dataDTO.cateName);
            initRecyclerView();
        }

        binding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        binding.lnPlayAll.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (music_list.size() > 0 && MusicMainActivity.serviceBinder != null) {
                    MusicMainActivity.result_type = "";
                    MusicMainActivity.serviceBinder.addPlayList(music_list, music_list.get(0));
                }
            }
        });
        initPlayerStateChangeListener();
    }

    private void initRecyclerView() {
        final LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        binding.rcvMusicList.setLayoutManager(layoutManager);
        music_list.clear();
        for (CategoryMusicThreeData.DataDTO.MusicListDTO musicListDTO : dataDTO.musicList) {
            music_list.add(new Music(musicListDTO.id, musicListDTO.musicName, musicListDTO.musician, musicListDTO.musicDuration,
                    musicListDTO.region, musicListDTO.musicUrl, musicListDTO.favorite == 1,
                    0, 0, "test_result",
                    (MusicMainActivity.serviceBinder.isPlaying() && MusicMainActivity.serviceBinder.getCurrentMusic().musicName.equals(musicListDTO.musicName)),
                    true, false));
        }
        mAdapter = new MusicPlayListAdapter(this, music_list);
        binding.rcvMusicList.setAdapter(mAdapter);
        if (music_list.size() <= 0) {
            binding.lnPlayAll.setVisibility(View.GONE);
        }

    }


    @Subscribe
    public void onEvent(EventBusMessage message) {
        Log.i("lgb", "onEvent: " + message.getmessage());
        //接收以及处理数据
        if (message.getmessage().equals(Constants.Add_Favorite)) {
            for (Music music : music_list) {
                if (music.id == message.getMusicId()) {
                    music.isFav = true;
                }
            }
            needRefresh = true;
        } else if (message.getmessage().equals(Constants.Cancel_Favorite)) {
            for (Music music : music_list) {
                if (music.id == message.getMusicId()) {
                    music.isFav = false;
                }
            }
            needRefresh = true;
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (needRefresh && mAdapter != null) {
            mAdapter.notifyDataSetChanged();
        }
        needRefresh=false;
    }

    @Override
    public void finish() {
        super.finish();
        EventBus.getDefault().unregister(this);
        MusicMainActivity.serviceBinder.unregisterOnStateChangeListener(listenr);
    }


    public void initPlayerStateChangeListener(){
        MusicMainActivity.serviceBinder.registerOnStateChangeListener(listenr);
    }

    //实现监听器监听MusicService的变化，
    private MusicService.OnStateChangeListenr listenr = new MusicService.OnStateChangeListenr() {
        @Override
        public void onPlayProgressChange(long played, long duration) {

        }

        @Override
        public void onPlay(final Music item) {
            Log.i("lgb", "onPlay: ");
            for(Music music:music_list){
                music.isPlaying=false;
                if(music.musicName.equals(item.musicName)){
                    music.isPlaying=true;
                }
            }
            if(mAdapter!=null){
                mAdapter.notifyDataSetChanged();
            }
        }

        @Override
        public void onPause() {
            //变为暂停状态时

        }
    };








}